<?php
declare (strict_types=1);

namespace app\admin\controller\media;

use app\common\controller\BaseController;
use app\admin\model\media\Article as ArticleModel;
use app\admin\model\media\Module as ModuleModel;
use app\common\library\media\Crawler;

use think\exception\ValidateException;
use think\facade\Cache;

class Article extends BaseController
{

    /**
     * @var ArticleModel
     */
    protected $model;
    /**
     * @var ModuleModel
     */
    private $ModuleModel;

    public function initialize()
    {
        parent::initialize();

        $this->model = new ArticleModel;
        $this->ModuleModel = new ModuleModel;
    }

    public function syncArticle()
    {
        $module_id = $this->request->param('module_id', 0, 'intval');
        $module = $this->ModuleModel->where('id', '=', $module_id)->find();
        if (!$module) {
            return $this->error('模块不存在');
        }
        $key = 'media_sync_article';
        $cache = Cache::get($key);
        if (empty($cache)) {
            Cache::set($key, $module_id, 3);

            //采集模块的文章
            $config = json_decode($module['rules'], true);
            $crawler = new Crawler($config);
            $url = isset($config['url']) ? $config['url'] : $module['url'];
            $html = $crawler->getWebsiteHtml($url);
            $dataList = $crawler->getHtmlData();
            if (empty($dataList) || isset($dataList[0]['title']) == false) {
                $this->error('采集规则无效');
            }
            $this->model->saveArticleList($dataList, $module);

            $this->success('操作成功');
        } else {
            $this->error('操作频繁，请稍后再试');
        }
    }

}